package spring.cloud.tasks.executor.task;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class TaskItemExecuteTimeoutTask implements Runnable {

    private TaskItemExecuteTask taskItemExecuteTask;

    public TaskItemExecuteTimeoutTask(TaskItemExecuteTask taskItemFutureTask) {
        this.taskItemExecuteTask = taskItemFutureTask;
    }

    @Override
    public void run() {
        try {
            TaskItemExecute taskItemFutureTaskCaller = taskItemExecuteTask.getTaskItemExecute();
            if (!taskItemExecuteTask.isDone() && taskItemFutureTaskCaller.setTimeout()) {
                String taskId = taskItemFutureTaskCaller.getTaskId();
                Integer taskItemIndex = taskItemFutureTaskCaller.getTaskItemIndex();
                LogUtils.info(log, taskId, "Force stop timeout job, jobName:{}, item:{}", taskId, taskItemIndex);
                // 调用beforeTimeout函数
                taskItemFutureTaskCaller.beforeTimeout();
                // 强杀
                TaskItemExecuteTask.killRunningBusinessThread(taskItemExecuteTask);
            }
        } catch (Throwable t) {
            TaskItemExecute taskItemFutureTaskCaller = taskItemExecuteTask.getTaskItemExecute();
            if (taskItemFutureTaskCaller != null) {
                LogUtils.warn(log, taskItemFutureTaskCaller.getTaskId(), "Failed to force stop timeout job", t);
            } else {
                LogUtils.warn(log, "unknown job", "Failed to force stop timeout job", t);
            }
        }
    }

}
